/*
 * @Description:
 * @Author: nardy.sanghx
 * @LastEditors: nardy.sanghx
 * @Date: 2019-05-10 18:16:31
 * @LastEditTime: 2019-11-19 14:07:20
 */
// 正则匹配
let Pattern = {
  isEmpty: /(^\s*)|(\s*$)/g,
  isMobile: /^1[3|4|5|6|7|8][0-9]{9}$/,
  isCnAndEn: /^[\u4E00-\u9FA5]+$/,
  isCnAndEnAndNum: /^[\u4e00-\u9fa5-a-zA-Z0-9]+$/,
  isUserName: /^[(\u4e00-\u9fa5)a-zA-Z]+$/,
  isPassword: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
  isAuthCode: /^[0-9]{6}$/,
  isTelAndMobile: /^(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})$/
}

const validator = {
  /**
   * 执行正则表达式
   * @param pattern 校验的正则表达式
   * @param strValue 校验的值
   * @returns {boolean}
   */
  executeExp: function (pattern, strValue) {
    return pattern.test(strValue)
  },
  /**
   * 判断字符串是否为空
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isEmpty: function (strValue) {
    strValue = strValue.replace(Pattern.isEmpty, '')
    return strValue.length === 0
  },
  /**
   * 判断字符串是否非空
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isNotEmpty: function (strValue) {
    return !this.isEmpty(strValue)
  },
  /**
   * 判断是否为中文
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isCnAndEn: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }

    return this.executeExp(Pattern.isCnAndEn, strValue)
  },
  /**
   * 判断是否为中英文、数字及'-'
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isCnAndEnAndNum: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }

    return this.executeExp(Pattern.isCnAndEnAndNum, strValue)
  },
  /**
   * 判断是否为用户名
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isUserName: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }

    return this.executeExp(Pattern.isUserName, strValue)
  },
  /**
   * 判断验证码格式
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isAuthCode: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }
    return this.executeExp(Pattern.isAuthCode, strValue)
  },
  /**
   * 判断是否为手机号码
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isMobile: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }
    return this.executeExp(Pattern.isMobile, strValue)
  },
  /**
   * 判断是否为手机或电话号码
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isTelAndMobile: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }
    return this.executeExp(Pattern.isTelAndMobile, strValue)
  },
  /**
   * 判断是否符合密码规则
   * @param strValue 校验的值
   * @returns {boolean}
   */
  isPassword: function (strValue) {
    if (this.isEmpty(strValue)) {
      return false
    }
    return this.executeExp(Pattern.isPassword, strValue)
  },
  /**
   * 对象是否为空
   * @param obj 检验对象
   * @returns {boolean}
   */
  isEmptyObj: (obj) => {
    return Object.keys(obj).length === 0
  },
  /**
   * 是否在范围长度内
   * @param 范围数组 [1, 10] 长度在1-10内
   * @returns {boolean}
   */
  isLenRange: (strValue, lenArr) => {
    return strValue.length >= lenArr[0] && strValue.length <= lenArr[1]
  },
  /**
   * 是否在数值范围内
   * @param 范围数组 [1, 10] 数值在1-10内
   * @returns {boolean}
   */
  isNumRange: (numValue, numArr) => {
    return numValue >= numArr[0] && numValue <= numArr[1]
  }

}

let error = ''

/**
 * @description: yanz 
 * const rule = [
   {name: 'stid', checkType: 'notnull', errorMsg: '请选择学员'}
 ]
  let checkRes = check(this.studentData, rule)
  if (checkRes) {
  } else {
    wx.showToast({
      title: utils.error,
      icon: 'none',
      duration: 2000
    })
  }
 * @param {type} 
 * @return: 
 */

export function check (data, rule) {
  for (var i = 0; i < rule.length; i++) {
    if (!rule[i].checkType) { return true }
    if (!rule[i].name) { return true }
    if (!rule[i].errorMsg) { return true }
    if (!data[rule[i].name]) { this.error = rule[i].errorMsg; return false }
    switch (rule[i].checkType) {
      case 'string':
        var reg = new RegExp('^.{' + rule[i].checkRule + '}$')
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
      case 'int':
        var reg = new RegExp('^(-[1-9]|[1-9])[0-9]{' + rule[i].checkRule + '}$')
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
        break
      case 'between':
        if (!this.isNumber(data[rule[i].name])) {
          this.error = rule[i].errorMsg
          return false
        }
        var minMax = rule[i].checkRule.split(',')
        minMax[0] = Number(minMax[0])
        minMax[1] = Number(minMax[1])
        if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
          this.error = rule[i].errorMsg
          return false
        }
        break
      case 'betweenD':
        var reg = /^-?[1-9][0-9]?$/
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        var minMax = rule[i].checkRule.split(',')
        minMax[0] = Number(minMax[0])
        minMax[1] = Number(minMax[1])
        if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
          this.error = rule[i].errorMsg
          return false
        }
        break
      case 'betweenF':
        var reg = /^-?[0-9][0-9]?.+[0-9]+$/
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        var minMax = rule[i].checkRule.split(',')
        minMax[0] = Number(minMax[0])
        minMax[1] = Number(minMax[1])
        if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
          this.error = rule[i].errorMsg
          return false
        }
        break
      case 'same':
        if (data[rule[i].name] != rule[i].checkRule) { this.error = rule[i].errorMsg; return false }
        break
      case 'notsame':
        if (data[rule[i].name] == rule[i].checkRule) { this.error = rule[i].errorMsg; return false }
        break
      case 'email':
        var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
      case 'phoneno': // 电话
        var reg = /^1[0-9]{10,10}$/
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
      case 'zipcode':
        var reg = /^[0-9]{6}$/
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
      case 'reg':
        var reg = new RegExp(rule[i].checkRule)
        if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false }
        break
      case 'in':
        if (rule[i].checkRule.indexOf(data[rule[i].name]) == -1) {
          this.error = rule[i].errorMsg; return false
        }
        break
      case 'notnull':
        if (data[rule[i].name] == null || data[rule[i].name].length < 1) { this.error = rule[i].errorMsg; return false }
        break
    }
  }
  return true
}




export function isNumber (checkVal) {
  var reg = /^-?[1-9][0-9]?.?[0-9]*$/
  return reg.test(checkVal)
}

// 微信加载框
function wxshowLoading (title) {
  wx.showLoading({
    title
  })
}

// 微信浮层
function wxshowToast (title, icon = 'success') {
  wx.showToast({
    title,
    icon,
    duration: 2000,
    mask: true
  })
}

// 微信弹窗
function wxshowModal (title, content) {
  wx.showModal({
    title,
    content,
    showCancel: false
  })
}

export function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function parseTimeDate (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  // eslint-disable-next-line camelcase
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    // eslint-disable-next-line standard/computed-property-even-spacing
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  // eslint-disable-next-line camelcase
  return time_str
}

export function date2Timestamp (date) {
  if (date) {
    let newDate = new Date(date).getTime()
    return newDate
  } else {
    return ''
  }
}

export function ages (str) {
  var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/)
  if (r == null) return false
  var d = new Date(r[1], r[3] - 1, r[4])
  if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
    var Y = new Date().getFullYear()
    return Y - r[1]
  }
}

export function textBecomeImg (text, fontsize, fontcolor) {
  let canvas = wx.createCanvasContext('canvas')
  canvas.setFontSize(20)
  canvas.fillText(text, 100, 100) // 必须为（0,0）原点
  canvas.draw()
  // var dataUrl = canvas.toDataURL('image/png')// 注意这里背景透明的话，需要使用png
  return canvas
}

export default {
  error,
  validator,
  check,
  wxshowLoading,
  wxshowToast,
  wxshowModal,
  formatNumber,
  formatTime,
  parseTimeDate,
  ages,
  textBecomeImg,
  date2Timestamp
}
